import React from 'react';

import { Table, Space, Popconfirm, notification as Notification } from 'antd';
import { bookClassificationTreeVo, deleteBookClassification } from '../../../api/bookClassification';

import './BookClassification.scss';
import BookClassificationForm from './components/BookClassificationForm';

class BookClassification extends React.Component {
  state = {
    checkStrictly: false,
    data: [],
    loading: false,
    tableHeight: 400,
    editForm: {
      visible: false,
      type: 'add',
      data: {}
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      checkStrictly: false,
      data: [],
      loading: false,
      tableHeight: 400,
      editForm: {
        visible: false,
        type: 'add',
        data: {}
      }
    };
  }

  componentDidMount() {
    this.handleRefresh();

    window.addEventListener('resize', this.handleResize);
    setTimeout(() => {
      this.handleResize();
    }, 1);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  handleResize = (e) => {
    const element = document.getElementsByClassName('bookClassification-table-wrapper')[0];
    console.log(element, typeof element, 'element');
    if (element) {
      const offsetHeight = element.offsetHeight;
      const tableHeight = offsetHeight - 64 - 58 - 4;
      this.setState({
        tableHeight: tableHeight
      });
    }
  };

  columns = [
    {
      title: '分类法序号',
      dataIndex: 'classification',
    },
    {
      title: '分类名称',
      dataIndex: 'name',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      width: 300,
      // eslint-disable-next-line react/display-name
      render: (text, record) => {
        if (record.aaa) {
          return '';
        }
        return (
          <Space size="middle">
            <a onClick={(e) => {
              this.handleAdd(record);
              e.stopPropagation();
            }}>添加</a>
            <a onClick={(e) => {
              this.handleEdit(record);
              e.stopPropagation();
            }}>修改</a>
            {
              !record.children || record.children.length <= 0
                ? (<Popconfirm
                  title="确认删除?"
                  cancelText="取消"
                  okText="确定"
                  okType=""
                  onConfirm={(e) => {
                    this.handleDelete(record);
                    e.stopPropagation();
                  }}>
                  <a>删除</a>
                </Popconfirm>) : ''
            }
          </Space>
        );
      }
    },
  ];

  setEditForm = (data) => {
    this.setState({
      userForm: Object.assign(this.state.editForm, data)
    });
  };

  closeEditForm = () => {
    this.setEditForm({
      visible: false,
      type: 'add',
      data: {}
    });

    this.handleRefresh();
  };

  handleAdd = (data) => {
    data = JSON.parse(JSON.stringify(data));
    delete data.children;
    this.setEditForm({
      visible: true,
      type: 'add',
      data: data
    });
  };

  handleDelete = ({ id: bookClassificationId }) => {
    deleteBookClassification(bookClassificationId).then(({ data }) => {
      Notification.success({
        message: `删除${data.name}成功`,
        duration: 2
      });
      this.handleRefresh();
    }).catch((e) => {
      console.log(e, typeof e, 'e');
    });
  };

  handleEdit = (data) => {
    data = JSON.parse(JSON.stringify(data));
    delete data.children;
    this.setEditForm({
      visible: true,
      type: 'edit',
      data: data
    });
  };

  handleRefresh = () => {
    this.setState({
      loading: true
    });
    bookClassificationTreeVo().then(({ data }) => {
      function deleteEmptyChildren(records) {
        records.forEach((record) => {
          if (record && record.children) {
            if (record.children.length <= 0) {
              delete record.children;
            } else {
              deleteEmptyChildren(record.children);
            }
          }
        });
      }

      deleteEmptyChildren(data);
      this.setState({
        data
      });
    }).catch((e) => {
      console.log(e, typeof e, 'e');
    }).finally(() => {
      this.setState({
        loading: false
      });
    });
  };

  render() {
    const { data, loading, tableHeight, editForm } = this.state;
    const { visible: userFormVisible, type: userFormType, data: editFormData } = editForm;
    return (
      <div className="bookClassification-list-container">
        <BookClassificationForm visible={userFormVisible} type={userFormType} onClose={this.closeEditForm}
          data={editFormData}/>
        <div className="bookClassification-table-wrapper">
          <Table
            loading={loading}
            rowKey={(record) => record.id}
            columns={this.columns}
            dataSource={data}
            scroll={{ y: tableHeight }}
            pagination={{ hideOnSinglePage: true }}
          />
        </div>
      </div>
    );
  }
}


export default BookClassification;
